//
//  SEInspListDetailVC.swift
//  SBSafetyApp
//
//  Created by Lina on 2022/12/11.
//
// 【首页-维保服务】维修工程师-巡检明细

import Foundation
import UIKit

class SEInspListDetailVC: SubLevelViewController {
    let detailV = SEInspListDetailView()
    
    var modal: ParListModal!

    var param = ParRecordParam()

    init(withModal _modal: ParListModal) {
        super.init(nibName: nil, bundle: nil)
        self.modal = _modal
        self.param.formId = _modal.formId
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        title = "巡检明细"
        view.backgroundColor = .bg
        setupUI()
        reloadData()
    }
    
    func reloadData() {
        detailV.updateUI(withModal: modal)
        
        view.showToastActivity()
        API.getEngineerDetail(withParam: EngineerParam(formId: modal.formId)) { responseModel in
            DispatchQueue.main.async {
                self.detailV.updateUI(withModal: responseModel.model)
                self.view.hideToastActivity()
            }
        }
    }
    
    @objc func submitTapped() {
        let unChecks = detailV.detailV.records.filter({ $0.status == "2" })
        
        if unChecks.count > 0 {
            view.showToast(witMsg: "请完成「\(unChecks[0].tmplName ?? "巡检任务")」")
            return
        }
        
        if detailV.signV.img == nil {
            view.showToast(witMsg: "请完成签名")
            return
        }
        
        view.showToastActivity()
        
        // 上传图片
        let listParams = detailV.detailV.records

        if listParams.count == 0 {
            uploadSign()
            return
        }
        
        var uParam: [InspUploadParam] = []
        
        for listParam in listParams {
            if listParam.images == nil || listParam.images?.count == 0 {
                uParam.append(InspUploadParam(item: listParam))
                if uParam.count == listParams.count {
                    self.param.patrolRecord = uParam
                    self.uploadSign()
                }
            } else {
                var uploadindex = 0
                var imageUrlList: [[String: String]] = []
                if let images = listParam.images {
                    for img in images {
                        let path = FilesManager.shared.saveImage(img: img.resizedTo1MB() ?? img)
                        API.postYjwxUpload(withImage: path!) { responseModel in
                            if responseModel.model?.imgUrl != nil {
                                imageUrlList.append(["imgUrl": responseModel.model!.imgUrl!])
                            }
                            uploadindex += 1
                            if listParam.images!.count == uploadindex {
                                uParam.append(InspUploadParam(item: listParam, images: imageUrlList))
                                if uParam.count == listParams.count {
                                    self.param.patrolRecord = uParam
                                    self.uploadSign()
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    
    func uploadSign() {
        let path = FilesManager.shared.saveImage(img: detailV.signV.img!)
        if path != nil {
            API.postStandingBookUpload(withImage: path!) { responseModel in
                self.param.bxqm = responseModel.model?.imgUrl
                self.didSubmint()
            }
        }
    }
    
    func didSubmint() {
        do {
            let data: Data = try JSONEncoder().encode(param)
            let string = String(data: data, encoding: String.Encoding.utf8)
            API.postParRecord(withParam: CommonJsonParam(data: string)) { responseModel in
                self.view.hideToastActivity()
                if responseModel.errorCode == .Success {
                    self.view.showToast(witMsg: responseModel.errorMessage)
                    NotificationCenter.default.post(name: NotiInsp, object: nil)
                    self.navigationController?.popViewController(animated: true)
                }
            }
        } catch {
            print("postParRecord error", error)
        }
    }
    
    func setupUI() {
        detailV.submitBtn.addTarget(self, action: #selector(submitTapped), for: .touchUpInside)
        view.addSubview(detailV)
        detailV.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.top.equalTo(view.safeAreaLayoutGuide.snp.top)
            make.bottom.equalTo(view.safeAreaLayoutGuide.snp.bottom)
        }
    }
}
